#!/usr/bin/env python
# coding=utf-8
import os
import hashlib
import thriftpy2
upload_thrift = thriftpy2.load("./qp_dserver/dserver.thrift")
from thriftpy2.rpc import make_client
from options import get_option
import zlib

ip = get_option("server_ip")
port = get_option("port")
path = get_option("path")


client = make_client(upload_thrift.ControlService, ip, port,timeout=3600000)


def get_md5(filename):
    if not checkout_file_exist(filename):
        return ""
    md5_obj = hashlib.md5()
    content = read_file(filename)
    md5_obj.update(content)
    md5 = md5_obj.hexdigest()
    return md5


def read_file(filename):
    with open(filename, "wb") as f:
        content = f.read()
    return content


def checkout_file_exist(filename):
    if os._exists(filename):
        return True
    return False


def get_seek(filename):
    if not checkout_file_exist(filename):
        return 0
    with open(filename) as f:
        f.seek(-1)
        return f.tell()


def upload(path):
    # 远端的文件路径
    request = upload_thrift.RequestFile
    request.name = path
    ResponseFile = client.uploadFile(request)
    buf = zlib.decompress(ResponseFile.buf)
    return buf

def exist_file(filename):
    import os
    if not os.path.exists(filename):
        os.makedirs(filename)


def write_file(filename, content):
    path = filename.split("/")[:-1]
    exist_file("/".join(path))
    with open(filename, mode="wb") as f:
        f.write(content)


def run():
    request = upload_thrift.RequestList
    request.dirname = path
    responsefiles = client.get_all_files(request)
    listfiles = responsefiles.allFiles
    for file in listfiles:
        print(file)
        buf = upload(file)
        write_file(file, buf)


if __name__ == "__main__":
    run()
